package dao;

import pojo.Student;
import utils.DataConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class StudentDao {

    public int addStudents(Student s) {
        int flag = 0;

        Connection conn = DataConn.getConn();
        String sql = "INSERT INTO student(sid, sname, ssex, sphone, sage) VALUES (?, ?, ?, ?, ?)";
//        String sql1 = "select *from student";

        List<Student> list = null;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            // 直接使用传入的Student对象's'，而不是新建一个
            pst.setString(1, s.getSid());
            pst.setString(2, s.getSname());
            pst.setString(3, s.getSsex());
            pst.setString(4, s.getSphone());
            pst.setLong(5, s.getSage());
            flag = pst.executeUpdate();
            System.out.println("Executing SQL: " + sql);
        } catch (SQLException e) {
            throw new RuntimeException("Error inserting student data", e);
        }
        return flag;
    }
    public int delStuById(String sid){
        int flag=0;
         Connection conn = DataConn.getConn();
         String sql="delete from student where sid=?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,sid);
            flag=ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
        return flag;
    }
    public int updata(Student s) {
        int flag = 0;

        Connection conn = DataConn.getConn();
        String sql = "update student set sphone=?,sname=? where sid=? ";

        try  {
            PreparedStatement pst = conn.prepareStatement(sql);
            // 直接使用传入的Student对象's'，而不是新建一个
            pst.setString(1, s.getSphone());
            pst.setString(3, s.getSid());
            pst.setString(2, s.getSname());
            flag = pst.executeUpdate();
            System.out.println("Executing SQL: " + sql);
//                }
        } catch (SQLException e) {
            throw new RuntimeException("Error inserting student data", e);

        }
        return flag;
    }
}